'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 副本扫荡
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var copyConf = require('../../../config/copyConf');
var copyRewardService = require('../../../services/copyRewardService');
var roleService = require('../../../services/roleService');
var rewardService = require('../../../services/rewardService');
var PlayerManager = require('../../../libs/playerManager');
var dataApi = require('../../../libs/dataApi');
var taskService = require('../../../services/taskService');
var constantUtil = require('../../../util/constantUtil.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 扫荡
 * @param  {[type]}   msg     [description]
 * @param  {[type]}   session [description]
 * @param  {Function} next    [description]
 * @return {[type]}           [description]
 */
Handler.prototype.sweep = function (msg, session, next) {
    var role_id = session.uid;
    var copy_id = msg.copy_id;
    var num = msg.num || 1;

    if (!copy_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    if (num > 20) {
        num = 20;
    }

    var player_manager = new PlayerManager(role_id);
    var sweep_list = [];
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'copy', 'bag', 'build', 'soldier', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb);
            },
            // jshint maxstatements:50
            function (cb) {
                var role_model = player_manager.role;
                var copy_model = player_manager.copy;

                var vip_lv = role_model.vip;
                if (num > 1) {
                    if (vip_lv < constantUtil.value('carbon_clean_vip_lvl')) {
                        return next(null, {
                            code: Code.USER_VIP_LV_NOT_PRIVILEGE
                        });
                    }
                }
                var copy_item = copy_model.getCopy(copy_id);
                if (!copy_item || copy_item.getStar() < 3) {
                    return next(null, {
                        code: Code.COPY_STAR_NEED_THREE
                    });
                }

                // 获取配置
                var copy_conf = copyConf.getCopyConf(copy_id);
                if (!copy_conf) {
                    return next(null, {
                        code: Code.COPY_NOT_EXIST
                    });
                }

                // 扣除体力
                if (!roleService.subEnergy(player_manager, moduleType.MDL_COPY, operationType.OPR_COPY_FIGHT, copy_conf.sp_cost * num)) {
                    return next(null, {
                        code: Code.USER_SP_NOT_ENOUGH
                    });
                }

                if (copy_conf.difficulty == 2) {
                    // 判断精英副本次数
                    if (!copy_model.addHardCarbonTimes(copy_id)) {
                        return next(null, {
                            code: Code.COPY_HARD_FIGHT_TIMES_EXCEEDED
                        });
                    }
                }

                for (var i = 0; i < num; i++) {
                    // // 判断是否还有扫荡次数
                    // if (copy_model.sweep_num >= copy_model.total_sweep_num) {
                    //     return next(null, {
                    //         code: Code.COPY_SWEEP_NUM_REACH_MAX
                    //     });
                    // }
                    // copy_model.sweep_num++;

                    // 添加奖励
                    var random_reward_list = copyRewardService.getRandomRewardList(role_model.getJob(), copy_id);
                    if (!random_reward_list) {
                        return next(null, {
                            code: Code.REWARD_ERROR
                        });
                    }
                    rewardService.addRewardListToRole(player_manager, random_reward_list, moduleType.MDL_COPY, operationType.OPR_COPY_FIGHT);

                    var fix_reward_list = copyRewardService.getFixRewardList(role_model.getJob(), copy_id);
                    if (!fix_reward_list) {
                        return next(null, {
                            code: Code.REWARD_ERROR
                        });
                    }
                    rewardService.addRewardListToRole(player_manager, fix_reward_list, moduleType.MDL_COPY, operationType.OPR_COPY_FIGHT);

                    var reward_list = _.union(random_reward_list, fix_reward_list);

                    sweep_list.push({
                        reward_list: reward_list
                    });

                    // 增加副本统计
                    taskService.addPassCopyNum(player_manager);
                }
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    sweep_list: sweep_list
                }
            });
        }
    );
};

// 购买扫荡次数
Handler.prototype.buyNum = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'copy', 'build', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb);
            },
            // jshint maxstatements:50
            function (cb) {
                var role_model = player_manager.role;
                var copy_model = player_manager.copy;

                var buy_sweep_num = copy_model.buy_sweep_num;
                var carbon_sweep_conf = dataApi.carbon_sweep.findById(buy_sweep_num + 1);
                if (!carbon_sweep_conf) {
                    return next(null, {
                        code: Code.COPY_SWEEP_CAN_NOT_BUY
                    });
                }

                if (!roleService.subDiamond(player_manager, moduleType.MDL_COPY, operationType.OPR_COPY_BUY_SWEEP, carbon_sweep_conf.cost_point)) {
                    return next(null, {
                        code: Code.USER_DIAMOND_NOT_ENOUGH
                    });
                }

                copy_model.buy_sweep_num++;
                copy_model.total_sweep_num++;
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};
